<?php

namespace common\logics\order;

use Yii;
use yii\db\Exception;
use common\models\shop\ShopOrder;

/**
 * 订单日志记录
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class RecordOrderLog extends \common\models\shop\ShopOrderLog {

    /**
     * @return string
     */
    public static function generateHandleMessageByOrderStatus($status, $params = []) {
        return Yii::t('order', 'HandleLog_' . ShopOrder::attributeConstName('status', $status), $params);
    }

    /**
     * 记录订单日志
     * @return bool
     */
    public static function record($order, $message = null, $operator = null) {
        try {
            static::safeRecord($order, $message, $operator);
        } catch (Exception $e) {
            Yii::error($e->getMessage());
            return false;
        }
        return true;
    }

    /**
     * 记录订单日志
     * @throws Exception
     * @return static
     */
    public static function safeRecord($order, $message = null, $operator = null) {
        if (!$message) {
            $message = static::generateHandleMessageByOrderStatus($order->status, $order->attributes);
        }
        $model = static::instance();
        $model->setAttributes([
            'order_id' => $order->id,
            'user_id' => $order->user_id,
            'type' => 0,
            'data' => $message,
            'admin_id' => (int) $operator,
            'order_status' => $order->status,
        ]);
        if (!$model->save()) {
            throw new Exception('订单优惠内容保存失败！');
        }
        return $model;
    }

}
